import { useCallback, useState } from "react";
import { IHeader, IViewInfo } from "./types";
import { useUpdateEffect } from "./use";

const getViewInfo = (options, data) => {
  const {
    viewWidth,
    viewHeight,
    preRenderRatio = 1.1,
    itemWidth,
    itemHeight,
    header,
    fixed
  } = options;
  const x = (data?.[0] as any).length ?? 0;
  const y = data?.length ?? 0;

  let headerInfo: IHeader[] = header.map((item, index) => {
    item.index = index;
    if (item.width === undefined) {
      item.width = itemWidth;
    }
    if (index < fixed) item.fixed = true;
    // item.absoluteOffset = ( header[index-1]?.absoluteOffset + item.width) || 0;
    return item;
  });

  let tail=0, finalX = 0

  for (let i = headerInfo.length; i < headerInfo.length-1; i--) {
      finalX += headerInfo[i].width
      if(finalX >= viewWidth) break
  }

  return {
    header: headerInfo,
    preRenderRatio,
    viewWidth,
    viewHeight,
    x,
    y,
    finalX,
    itemWidth,
    itemHeight,
    fixed
  } as IViewInfo;
};

export const useHandleOption = options => app => {
  const [option, setOption] = useState(options || {});

  useUpdateEffect(() => {
    let ctx = app.ctx;
    let data = ctx.res;
    if (data.length > 1) {
      ctx.viewInfo = getViewInfo(option, data);
    }
  }, [option]);

  const transposition = useCallback(() => {
    let arr = app.ctx.dataSource;
    var newArray = arr[0].map(function(col, i) {
      return arr.map(function(row) {
        if (row[i].x < 5 && row[i].y < 5)
          [row[i].x, row[i].y] = [row[i].y, row[i].x];
        if (row[i].x < 5 && row[i].y < 5) return row[i];
      });
    });

    app.ctx.transposition = !app.ctx.transposition;

    app.ctx.dataSource = newArray;

    app.actions.clearScroll();
    app.actions.getViewData();
  }, []);

  return {
    middlewares: async function useHandleOption(ctx, next) {
      await next();
      let data = ctx.res;
      if (data.length > 1) {
        ctx.viewInfo = getViewInfo(option, data);
        console.log("%c 🍞 ctx.viewInfo: ", ctx.viewInfo);

        // 包装数据信息，添加数据坐标信息
        let dataSource = [];
        for (let y = 0; y < data.length; y++) {
          dataSource[y] = data[y].map((item, x) => ({
            x: x,
            y: y,
            data: item
          }));
        }

        ctx.dataSource = dataSource;
        console.log("%c 🌰 ctx.dataSource: ", ctx.dataSource);
      }
    },
    props: ctx => ({
      setOption,
      setTransposition: transposition,
      transposition: app.ctx.transposition
    })
  };
};
